<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Reminder extends MY_Controller {
    private $per_page  = '10';
    private $prev_link  = 'Prev';
    private $next_link  = 'Next';
    
    private $profilestatus = array("Initial","Application","Approve","Arrived","Issue","Return","Rejected","Appointment","Cancel");
    private $passtype = array("Other","WP","SP","EP");
    
    public function __construct(){
        parent::__construct();
        $this->load->model('reminder_model');
        $this->load->model('profile_model');
        $this->load->model('index_model');
        $this->load->model('user_model');
    }
    
    public function index($current_date=''){
        if($this->is_logged_in()){
            if($current_date == ''){
                $current_date = date("Y-M-d",time());
            }
            $year = date("Y",strtotime($current_date));
            $month = date("m",strtotime($current_date));
            $day = $this->getMonthLastDay($month, $year);
            $start_week = date("w",strtotime($year."-".$month.'-01'));
            $days = $this->getDays($day,$start_week,$year,$month,5);
            $lastmonth = $this->getlastMonth($current_date);
            $nextmonth = $this->getnextMonth($current_date);
            $current_day = date("d",time());
            $current_month = date("m",time());
            $current_year = date("Y",time());
            $thisday = -1;
            if($current_year == $year && $current_month == $month){
                $thisday = $current_day+$start_week-1;
            }
            $data = array(
                'days'=>$days,
                'current'=>date("M Y",strtotime($current_date)),
                'lastmonth'=>$lastmonth,
                'nextmonth'=>$nextmonth,
                'thisday'=>$thisday,
                'ispickup'=>FALSE
            );

            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('reminder/reminder_top');
            $this->load->view('reminder/index',$data);
            $this->load->view('reminder/reminder_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function pickuppaper($current_date=''){
        if($this->is_logged_in()){
            if($current_date == ''){
                $current_date = date("Y-M-d",time());
            }
            $year = date("Y",strtotime($current_date));
            $month = date("m",strtotime($current_date));
            $day = $this->getMonthLastDay($month, $year);
            $start_week = date("w",strtotime($year."-".$month.'-01'));
            $days = $this->getDays($day,$start_week,$year,$month,1);
            $lastmonth = $this->getlastMonth($current_date);
            $nextmonth = $this->getnextMonth($current_date);
            $current_day = date("d",time());
            $current_month = date("m",time());
            $current_year = date("Y",time());
            $thisday = -1;
            if($current_year == $year && $current_month == $month){
                $thisday = $current_day+$start_week-1;
            }
            $data = array(
                'days'=>$days,
                'current'=>date("M Y",strtotime($current_date)),
                'lastmonth'=>$lastmonth,
                'nextmonth'=>$nextmonth,
                'thisday'=>$thisday,
                'ispickup'=>TRUE
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('reminder/reminder_top');
            $this->load->view('reminder/index',$data);
            $this->load->view('reminder/reminder_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    function getMonthLastDay($month,$year) {
        switch ($month) {
            case 4 :
            case 6 :
            case 9 :
            case 11 :
                $days = 30;
                break;
            case 2 :
                if ($year % 4 == 0) {
                    if ($year % 100 == 0) {
                        $days = $year % 400 == 0 ? 29 : 28;
                    } else {
                        $days = 29;
                    }
                } else {
                    $days = 28;
                }
                break;
            default :
                $days = 31;
                break;
        }
        return $days;
    }
    
    public function getDays($day,$week,$year,$month,$type=-1){
        $days = array();
        $index = 1;
        for($i = 0;$i < 42;$i++){
            $days[$i] = array();
            if($i < $day+$week && $i >= $week){
                $days[$i]['day'] = $index;
                if($index*1 < 10){
                    $days[$i]['date'] = $year.'-'.$month.'-0'.$index;
                }else{
                    $days[$i]['date'] = $year.'-'.$month.'-'.$index;
                }
                $userrole = $this->session->userdata('user')->role;
                $userid = 0;
                if($userrole == 1){
                    $userid = $this->session->userdata('user')->id;
                }
                $days[$i]['notices'] = $this->reminder_model->get5NoticeByDate($days[$i]['date'],$userid,$type);
                $index++;
            }else{
                $days[$i]['day'] = 0;
                $days[$i]['date'] = 0;
                $days[$i]['notices'] = array();
            }
        }
        return $days;
    }
    
    function getlastMonth($date){
        $timestamp=strtotime($date);
        $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));
        return $firstday;
    }
    
    function getNextMonth($date){
        $timestamp=strtotime($date);
        $arr=getdate($timestamp);
        if($arr['mon'] == 12){
            $year=$arr['year'] +1;
            $month=$arr['mon'] -11;
            $firstday=$year.'-0'.$month.'-01';
        }else{
            $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
        }
        return $firstday;
    }
    
    public function reminders($date,$ispickup=FALSE){
        $strtotime = strtotime($date);
        //根据时间戳查询出所有提醒
        $userrole = $this->session->userdata('user')->role;
        $userid = 0;
        if($userrole == 1){
            $userid = $this->session->userdata('user')->id;
        }
        $reminder = $this->reminder_model->getReminderByDate($strtotime,$userid,$ispickup);
        $data = array(
            'date'=>$date,
            'reminder'=>$reminder,
            'ispickup'=>$ispickup
        );
        $this->load->view('reminder/reminder',$data);
    }
    
    public function new_reminder(){
        //新增提醒
        $noticeid = $this->input->post("noticeid");
        $type = $this->input->post("type");
        $date = $this->input->post("noticedate");
        if($noticeid != NULL && $noticeid > 0){
            $data = array(
                'title'=>$this->input->post("title"),
                'comment'=>$this->input->post("comment"),
                'noticedate'=>strtotime($this->input->post("noticedate")),
                'noticetime'=>$this->input->post("noticetime"),
                'association'=>$this->input->post("association"),
                'updatetime'=>time()
            );
            $this->index_model->update("notice",$data,$noticeid);
            if($type==1){
                $data = array(
                    'fltno'=>$this->input->post("fltno"),
                    'terminal'=>$this->input->post("terminal"),
                    'arrivetime'=>strtotime($this->input->post("arrivetime"))
                );
                $this->index_model->update("pickup",$data,$this->input->post("pickupid"));
            }
        }else{
            $id = $this->reminder_model->new_reminder();
            if($type*1 == 1 && $id*1>0){
                $this->reminder_model->new_pickup($id);
            }
        }
        redirect("reminder/reminders/".$date);
    }
    
    public function deletenotice($id,$date,$ispickup=FALSE){
        //删除提醒
        $this->reminder_model->delete($id);
        redirect("reminder/reminders/".$date.'/'.$ispickup);
    }
    
    public function reminder_detail($id,$ispickup=FALSE){
        if(!$_POST){
        }else{
            //跟新reminder
            $this->reminder_model->update_reminder($id);
        }
        //根据id查询出消息
        $data['notice'] = $this->reminder_model->getNoticeByID($id);
        $data['ispickup'] = $ispickup;
        $this->load->view('reminder/reminder_detail',$data);
    }
    
    /**
     * 新增profile提醒
     * @param type $type 类型
     * @param type $time 时间
     * @param type $profileid
     */
    public function profile_reminders($type,$time,$profileid){
        //根据profileid查询很粗profile信息
        $profile = $this->profile_model->getProfileByID($profileid);
        if($profile['ordersn'] == NULL || trim($profile['ordersn']) == ''){//不存在订单
            $worker = $this->index_model->getWorkersByProfileID($profileid);
        }else{//存在订单
            $worker = $this->index_model->getWorkersByOrderID($profile['ordersn']);
        }
        //根据类型查询是否存在相关提醒
        //根据id查询出消息
        $notice = array();
        if($type > 0){
            $notice = $this->reminder_model->getNoticeByWorkerAndType($worker['id'],$type);
        }
        if($type*1 == 1 && count($notice)>1){
            //查询出接机信息
            $pickup = $this->reminder_model->getPickupByNoticeId($notice['id']);
        }else{
            $pickup = array(
                'id'=>0,
                'fltno'=>'',
                'terminal'=>'',
                'arrivetime'=>time(),
            );
        }
        if(count($notice) == 0){
            $notice = array(
                'id'=>0,
                'noticedate'=>time(),
                'noticetime'=>'',
                'title'=>'',
                'comment'=>'',
                'ispublic'=>0
            );
        }
        $data = array(
            'type'=>$type,
            'time'=>$time,
            'profilename'=>$profile['name'],
            'worker'=>$worker,
            'notice'=>$notice
        );
        
        $data['pickup'] = $pickup;
        $this->load->view('reminder/new_profile_reminders',$data);
    }
    
    public function summary(){
        if($this->is_logged_in()){
            $searchData = $this->getSummarySearchCondition();
            
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            if(0 == $current_page){
               $current_page = 1;
            }
            $offset   = ($current_page - 1 ) * $config['per_page'];//设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）

            $summary  = $this->reminder_model->get_summary($offset,$config['per_page'],$searchData);

            $config['base_url']           = base_url('reminder/summary?').
                    'sales='.$searchData['salesid'].'&status='.$searchData['status'].
                    '&passtype='.$searchData['passtype'].'&starttime='.$searchData['starttime'].
                    '&endtime='.$searchData['endtime'].'&condition='.$searchData['condition'].
                    '&ordername='.$searchData['ordername'].'&searchstatus='.$searchData['searchstatus'].
                    '&officer='.$searchData['officerid']."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $summary['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);
            
            $salesman = $this->user_model->getAllEmployeeUser();
            $officer = $this->user_model->getAllOffice();
            $data = array(
                'summary'  => $summary['res'],
                'total'   => $summary['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'searchData'=>$searchData,
                'salesman'=>$salesman,
                'officer'=>$officer,
                'passtype'=>$this->passtype,
                'status'=>$this->profilestatus
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('reminder/reminder_top');
            $this->load->view('reminder/summary',$data);
            $this->load->view('reminder/reminder_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }


    //根据查询条件导出EXCEL表
    public function export2excel(){
        if($this->is_logged_in()){
            $searchData = $this->getSummarySearchCondition();
            
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            if(0 == $current_page){
               $current_page = 1;
            }
            $offset   = ($current_page - 1 ) * $config['per_page'];//设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）

            $summary  = $this->reminder_model->get_summary_export($searchData);
            $passtype = $this->passtype;
            $status   = $this->profilestatus;
            
            $rs = $summary['res'];
            foreach ($rs as $key => $value) {
                $remd[0] = $value['name'];
                $remd[1] = $value['workname'];
                $remd[2] = isset($value['worktype'])?$passtype[$value['worktype']]:'';
                $remd[3] = $status[$value['status']];
                //申请时间
                if($searchData['status']==1){
                    $remd[4] = ($value['applytime'] != NULL&&$value['applytime'] != '')?date('Y-m-d H:m:s',$value['applytime']):'';
                }else if($searchData['status']==2){
                    $remd[4] = ($value['approvetime'] != NULL&&$value['approvetime'] != '')?date('Y-m-d H:m:s',$value['approvetime']):'';
                }else if($searchData['status']==3){
                    $remd[4] = ($value['arrivedtime'] != NULL&&$value['arrivedtime'] != '')?date('Y-m-d H:m:s',$value['arrivedtime']):'';
                }else if($searchData['status']==4){
                    $remd[4] = ($value['issuetime'] != NULL&&$value['issuetime'] != '')? date('Y-m-d H:m:s',$value['issuetime']): '';
                }else if($searchData['status']==5){
                    $remd[4] = ($value['returntime'] != NULL&&$value['returntime'] != '')? date('Y-m-d H:m:s',$value['returntime']): '';
                }else if($searchData['status']==6){
                    $remd[4] = ($value['rejectedtime'] != NULL&&$value['rejectedtime'] != '')? date('Y-m-d H:m:s',$value['rejectedtime']): '';
                }else if($searchData['status']==7){
                    $remd[4] = ($value['othertime'] != NULL&&$value['othertime'] != '')? date('Y-m-d H:m:s',$value['othertime']): '';
                }else if($searchData['status']==8){
                    $remd[4] = ($value['canceldate'] != NULL&&$value['canceldate'] != '')? date('Y-m-d H:m:s',$value['canceldate']): '';
                }else{
                    $remd[4] = ($value['createtime'] != NULL&&$value['createtime'] != '')? date('Y-m-d H:m:s',$value['createtime']): '';
                }
                $remd[5] = '';
                if($value['status']*1>3)
                {
                    $remd[5] = $value['wi']==0?'Y(R)':($value['wi']==1?'Y(B)':'N');
                }

                $remd[6] = '';
                if($value['status']*1>3)
                {
                    $remd[6] = $value['wici']==0?'Y(R)':($value['wici']==1?'Y(B)':'N');
                }
                $remd[7] = $value['username'];
                $remd[8] = $value['employeename'];
                $data[] = $remd;
            }
            //导出EXEL
            $this->load->library('PHPExcel');
            $this->load->library('PHPExcel/IOFactory');
            
            $objPHPExcel = new PHPExcel();
            $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,1,'Company Name');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,1,'Worker Name');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,1,'Permit type');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3,1,'Stats');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4,1,'Create Date');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5,1,'MI');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6,1,'WICI');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7,1,'Salseman');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8,1,'Interviewer');

            $col = 0;
            $row = 2;
            $objPHPExcel->setActiveSheetIndex(0);

            foreach ($data as $key => $value) {
                $col=0;

                foreach ($value as $k => $v) {
                    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row,$v);
                    $col++;
                }
                $row++;
            }

            $objPHPExcel->setActiveSheetIndex(0);
            $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="Report_'.date('Y-m-d').'.xls"');
            header('Cache-Control: max-age=0');
            $objWriter->save('php://output');

            //var_dump($data[0]);exit;
        }else{
            redirect('user/login');
        }
    }
    
    public function getSummarySearchCondition(){
        //查询条件
        $salesid = 0;
        $officerid = 0;
        $status = -1;
        $passtype = 0;
        $starttime = "";
        $endtime = "";
        $condition = "";
        $searchstatus = 0;
        $ordername = "p.id desc";
        if($_GET){
            $officerid = $this->input->get("officer")==0?0:$this->input->get("officer");
            $salesid = $this->input->get("sales")==0?0:$this->input->get("sales");
            $status = $this->input->get("status")==0?0:$this->input->get("status");
            $passtype = $this->input->get("passtype")==0?0:$this->input->get("passtype");
            $starttime = $this->input->get("starttime")==""?"":$this->input->get("starttime");
            $endtime = $this->input->get("endtime")==""?"":$this->input->get("endtime");
            $condition = $this->input->get("condition")==""?"":$this->input->get("condition");
            $searchstatus = $this->input->get("searchstatus")==""?0:$this->input->get("searchstatus");
            $ordername = $this->input->get("ordername")==""?"p.id desc":$this->input->get("ordername");
        }else if($_POST){
            $officerid = $this->input->post("officer")==0?0:$this->input->post("officer");
            $salesid = $this->input->post("sales")==0?0:$this->input->post("sales");
            $status = $this->input->post("status")==0?0:$this->input->post("status");
            $passtype = $this->input->post("passtype")==0?0:$this->input->post("passtype");
            $starttime = $this->input->post("starttime")==""?"":$this->input->post("starttime");
            $endtime = $this->input->post("endtime")==""?"":$this->input->post("endtime");
            $condition = $this->input->post("condition")==""?"":$this->input->post("condition");
            $searchstatus = $this->input->post("searchstatus")==""?0:$this->input->post("searchstatus");
            $ordername = $this->input->post("ordername")==""?"p.id desc":$this->input->post("ordername");
        }
        return array(
            'salesid'=>$salesid,
            'status'=>$status,
            'passtype'=>$passtype,
            'starttime'=>$starttime,
            'endtime'=>$endtime,
            'condition'=>$condition,
            'ordername'=>$ordername,
            'searchstatus'=>$searchstatus,
            'officerid'=>$officerid
        );
    }
    
    public function invoice(){
        if($this->is_logged_in()){
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            $condition = $this->input->post('condition') == NULL?
                    $this->input->get('condition'):$this->input->post('condition');
            if(0 == $current_page){
               $current_page = 1;
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"id desc");
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）       
            $invoice  = $this->reminder_model->get_invoice($offset,$config['per_page'],$ordername,$condition);
            $config['base_url']           = base_url('reminder/invoice?').'condition='.$condition."&ordername=".$ordername."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $invoice['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);

            $data = array(
                'invoices'  => $invoice['res'],
                'total'   => $invoice['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'condition'  =>  $condition,
                'ordername'=>$ordername
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('reminder/reminder_top');
            $this->load->view('reminder/invoice',$data);
            $this->load->view('reminder/reminder_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function newInvoice(){
        $this->form_validation->set_rules('client', 'Client', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['selfinfo'] = $this->reminder_model->getSelfInfo();
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('reminder/reminder_top');
            $this->load->view('reminder/newinvoice',$data);
            $this->load->view('reminder/reminder_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->reminder_model->newInvoice();
            redirect("reminder/invoice");
        }
    }
    
    public function deleteinvoice(){
        $this->reminder_model->deleteinvoice();
        redirect("reminder/invoice");
    }
    
    public function printInvoice($id){
        $data['selfinfo'] = $this->reminder_model->getSelfInfo();
        $data['invoice'] = $this->reminder_model->getInvoice($id);
        $this->load->view('templates/header');
        $this->load->view('templates/left');
        $this->load->view('reminder/reminder_top');
        $this->load->view('reminder/printinvoice',$data);
        $this->load->view('reminder/reminder_bottom');
        $this->load->view('templates/footer');
    }
}